#include "App.h"
#include "../XXqtDefine.h"
#include <QDebug>
#include "../Utility/XXlogger.h"

#define kReloadSS -99

App::App(int &argc, char **argv) : QApplication (argc, argv)
{
    _mainViewBlock = nullptr;
    _launchView = nullptr;
    _mainView = nullptr;
}

void App::configMainView(QWidget *mainView, bool showMaximized){
    _mainView = mainView;
    _showMaximized = showMaximized;
    installMainView(_mainView);
}
void App::configMainView(std::function<QWidget*(void)> mainView, bool showMaximized){
    _mainViewBlock = mainView;
    _showMaximized = showMaximized;
    _mainView = _mainViewBlock();
    installMainView(_mainView);
}
void App::configStyleSheetPath(const QString &filePath){
    _ssPath = filePath;
    if(_mainView){
        XXqtDefine::qssLoad(_mainView,_ssPath);
    }
}

int App::exec(){
    int ret = -1;
    bool first = true;
    do{
        showMainView(!first);
        first = false;
        ret = QApplication::exec();
    }while(ret==kReloadSS);
    return ret;
}

void App::installMainView(QWidget *widget){
    if(!_ssPath.isEmpty()){
        XXqtDefine::qssLoad(widget,_ssPath);
    }
    widget->installEventFilter(this);
    if(_showMaximized){
        connect(this,&App::sigShowMainView,widget,&QWidget::showMaximized,Qt::QueuedConnection);
    }
}
void App::showMainView(bool re){
    if(re){
        if(_mainViewBlock){
            if(_mainView){
                delete  _mainView;
            }
            _mainView = _mainViewBlock();
        }
        else{
            auto mw = qobject_cast<QWidget*>(_mainView->metaObject()->newInstance());
            if(_mainView){
                delete  _mainView;
            }
            _mainView = mw;
        }
        installMainView(_mainView);
    }

    _mainView->showNormal();
    if(_showMaximized){
        emit sigShowMainView();
    }
}
bool App::eventFilter(QObject *w, QEvent *e){
    if(w==_mainView && e->type()==QEvent::KeyPress){
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(e);
        if((keyEvent ->modifiers()& Qt::ControlModifier) != 0 && keyEvent ->key() == Qt::Key_R){
            exit(kReloadSS);
        }
    }
    return QApplication::eventFilter(w,e);
}
